package com.zoshine.zzg.controller;

import com.zoshine.zzg.annotation.DisableLoginCheck;
import com.zoshine.zzg.base.BaseResponse;
import com.zoshine.zzg.exception.AppException;
import com.zoshine.zzg.exception.ErrorMessage;
import com.zoshine.zzg.exception.SysException;
import com.zoshine.zzg.respons.AppResponse;
import com.zoshine.zzg.service.SystemParamService;
import com.zoshine.zzg.util.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 文件控制器，主要处理文件上传下载，及数据导入导出
 *
 * @author 贾俊峰
 * @time 2017/7/17 16:42
 */
@RestController
@RequestMapping("file")
public class FileController {
    private SystemParamService systemParamService;
    @Autowired
    public void setSystemParamService(SystemParamService systemParamService) {
        this.systemParamService = systemParamService;
    }

    private static final String DEFAULT_IMAGE = "/img/type/defaultGoodsImg.png";
    private static final int IMAGE_WIDTH = 300;
    private static final int IMAGE_HEIGHT = 300;

    private static List<String> imageTypeList = new ArrayList<>();
    static {
        imageTypeList.add("jpg");
        imageTypeList.add("jpeg");
        imageTypeList.add("png");
        imageTypeList.add("bmp");
    }
    @DisableLoginCheck
    @RequestMapping(value = "download/{path}/{filename}.{fileType}", method = RequestMethod.GET)
    public void download(HttpServletResponse response, @PathVariable String path, @PathVariable String filename,
            @PathVariable String fileType, String showName) throws IOException {

        filename = filename + "." + fileType;
        if (showName == null || showName.length() == 0) {
            showName = filename;
        } else {
            showName = URLEncoder.encode(showName, "utf-8") + "." + fileType;
        }

        File file = new File(systemParamService.getFileRepositoryRealPath()+"/"+path+"/"+filename);
        if (!file.exists()) {
            if (imageTypeList.contains(fileType)) {
                response.sendRedirect(DEFAULT_IMAGE);
                return;
            } else {
                throw new AppException(ErrorMessage.FILE_LINK_IS_INVALID);
            }
        }
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + showName + "\"");
        response.addHeader("Content-Length", "" + file.length());
        response.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        FileInputStream fileInputStream = new FileInputStream(file);

        byte[] bytes = new byte[1024];
        while (fileInputStream.read(bytes) != -1) {
            outputStream.write(bytes);
        }
        outputStream.flush();
        outputStream.close();
    }

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public BaseResponse upload(MultipartFile[] files) throws Exception {
        if (files == null || files.length == 0) {
            throw new AppException(ErrorMessage.FILE_CAN_NOT_BE_NULL);
        }

        List<UploadResult> list = new ArrayList<>();
        for (MultipartFile multipartFile : files) {
            UploadResult uploadResult = new UploadResult();
            uploadResult.setFileName(multipartFile.getOriginalFilename());

            String fileName = UUID.randomUUID().toString();
            // 获取文件的后缀名
            String suffixName = getFileType(multipartFile.getOriginalFilename());
            fileName += "." + suffixName;
            String d1 = new SimpleDateFormat("yyyyMMdd").format(new Date());

            File f = new File(systemParamService.getFileRepositoryRealPath() + "/" + d1 + "/" + fileName);
            if (!f.getParentFile().exists()) {
                boolean result = f.getParentFile().mkdirs();
                if (!result) {
                    throw new SysException(ErrorMessage.CREATE_FILE_ERROR);
                }
            }
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
            out.write(multipartFile.getBytes());
            out.flush();
            out.close();

            ImageUtil.zoomImage(f.getPath(),f.getPath(), 300, 300);

            uploadResult.setResult("success");
            uploadResult.setUrl("file/download/" + d1 + "/" + fileName);
            list.add(uploadResult);
        }
        return new AppResponse(list);
    }

    // 获取文件类型
    private String getFileType(String filename) {
        int index = filename.lastIndexOf(".") + 1;
        if (index == 0) {
            return "";
        } else {
            return filename.substring(index);
        }
    }
}


class UploadResult {
    private String fileName;
    private String result;
    private String url;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
